package com.buddies.lottery.data;

import android.text.TextUtils;

import com.buddies.lottery.App;
import com.tencent.bugly.crashreport.BuglyLog;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
    private static final int DEFAULT_TIME_OUT = 5;
    private static final int DEFAULT_READ_TIME_OUT = 5;

    private OkHttpClient mClient;
    private Retrofit mRetrofit;
    private String mBaseUrl;
    private CommonIntercepter mCommonIntercepter;

    private RetrofitManager() {
        mCommonIntercepter = new CommonIntercepter();
    }

    public void init(String baseUrl, String salt, Map<String, String> defaultHeaders, Map<String, String> defaultParams) {
        init(baseUrl, salt, defaultParams);
        setDefaultRequestHeaders(defaultHeaders);
    }

    public void init(String baseUrl, String salt, Map<String, String> defaultParams) {
        init(baseUrl, salt);
        setDefaultRequestParams(defaultParams);
    }

    public void init(String baseUrl, String salt) {
        init(baseUrl);
        setRequestSalt(salt);
    }

    public void init(String baseUrl) {
        mBaseUrl = baseUrl;
        init();
    }

    public void init() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                BuglyLog.d("NetRequest", message);
            }
        });
        logging.setLevel(App.LOGGABLE ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.BASIC);

        mClient = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addInterceptor(mCommonIntercepter)
                .addInterceptor(logging)
//                .dns(new OkhttpDns())
                .build();
        mRetrofit = new Retrofit.Builder().client(mClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(mBaseUrl)
                .build();
    }

    /**
     * 用于测试模式切换环境后重新初始化
     */
    public static void reInit() {
        getInstance().init();
    }

    public void setRequestSalt(String salt) {
        mCommonIntercepter.setRequestSalt(salt);
    }

    private static class SingletonHolder {
        private static final RetrofitManager INSTANCE = new RetrofitManager();
    }

    public static RetrofitManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public String getBaseUrl() {
        return mBaseUrl;
    }

    public void setBaseUrl(String baseUrl) {
        mBaseUrl = baseUrl;
    }

    /**
     * 设置请求默认请求参数
     * @param params 请求参数，key value
     */
    public void setDefaultRequestParams(Map<String, String> params) {
        mCommonIntercepter.setDefaultRequestParams(params);
    }

    /**
     * 设置请求默认请求头
     * @param params 请求头，key value
     */
    public void setDefaultRequestHeaders(Map<String, String> params) {
        mCommonIntercepter.setDefaultRequestHeaders(params);
    }

    /**
     * 获取对应的Service
     */
    public <T> T create(Class<T> service) {
        if (TextUtils.isEmpty(mBaseUrl)) {
            throw new IllegalArgumentException("Base URL required.");
        }

        if (mClient == null || mRetrofit == null) {
            throw new IllegalStateException("You didn't call the init method");
        }

        return mRetrofit.create(service);
    }
}
